package com.github.common.utils.spring;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.sql.Timestamp;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
import com.github.common.utils.io.JsonUtil;


/**
 * <p>User: Mu Yunlong
 * <p>Date: 2016年2月25日 下午5:24:49
 * <p>Version: 1.0
 */
public class SpringMessageConverterFastJson extends AbstractHttpMessageConverter<Object>{
    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
    private SerializerFeature[] serializerFeature;

    public SpringMessageConverterFastJson()
    {
      super(new MediaType("application", "json", DEFAULT_CHARSET));
    }

    public SerializerFeature[] getSerializerFeature() {
      return this.serializerFeature;
    }

    public void setSerializerFeature(SerializerFeature[] serializerFeatureP)
    {
      this.serializerFeature = serializerFeatureP;
    }

    public boolean canRead(Class<?> clazz, MediaType mediaType)
    {
      return true;
    }

    public boolean canWrite(Class<?> clazz, MediaType mediaType)
    {
      return true;
    }

    protected boolean supports(Class<?> clazz)
    {
      throw new UnsupportedOperationException();
    }

    protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage)
      throws IOException
    {
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      int i;
      while ((i = inputMessage.getBody().read()) != -1)
      {
        baos.write(i);
      }
      return JsonUtil.json2List(baos.toString(), clazz);
    }

    protected void writeInternal(Object o, HttpOutputMessage outputMessage)
      throws IOException
    {
      SerializeConfig sc = new SerializeConfig();
      sc.put(java.util.Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd HH:mm:ss"));
      sc.put(java.sql.Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd HH:mm:ss"));
      sc.put(Timestamp.class, new SimpleDateFormatSerializer("yyyy-MM-dd HH:mm:ss"));
      String jsonString = JSON.toJSONString(o, sc, this.serializerFeature);
      OutputStream out = outputMessage.getBody();
      out.write(jsonString.getBytes(DEFAULT_CHARSET));
      out.flush();
    }
}
